package com.sodaopen.study.controller;

import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Controller;
import org.springframework.ui.Model;
import org.springframework.web.bind.annotation.GetMapping;

import com.sodaopen.study.entity.ApiResult;
import com.sodaopen.study.entity.Chapter;
import com.sodaopen.study.entity.Course;
import com.sodaopen.study.service.ChapterService;
import com.sodaopen.study.service.CourseService;

import org.springframework.web.bind.annotation.PostMapping;
import org.springframework.web.bind.annotation.ResponseBody;

import java.util.List;

@Controller
public class ChapterController {

	@Autowired
	private CourseService courseService;

	@Autowired
	private ChapterService chapterService;

    @GetMapping("/content/chapter/list")
    public String listChapter(Integer courseId, Model model) {
    	Course course = courseService.findById(courseId);
    	
    	model.addAttribute("course", course);
    	return "chapter";
    }


	@GetMapping("/api/chapter/list")
	@ResponseBody
	public Object getChapterList(Integer courseId) {

		ApiResult result = new ApiResult();
		try{
			List<Chapter> list = chapterService.findByCourseId(courseId);
			result.setCode(0);
			result.setCount((long)list.size());
			result.setData(list);
		}catch (Exception e){
			result.setCode(1);
			result.setMsg("数据请求失败");
		}
		return result;
	}


	@GetMapping("/content/chapter/add")
	public String addChapter(Integer pid, Integer courseId, Model model) {
    	model.addAttribute("pid", pid);
    	model.addAttribute("courseId", courseId);
		return "chapter-add";
	}

	
	
	@PostMapping("/content/chapter/add")
	public String saveChapter(Chapter chapter, Model model) {
		if(chapter.getSort() == null){
			Integer maxSort = chapterService.findMaxSort(chapter.getPid(), chapter.getCourseId());
			chapter.setSort(maxSort+5);
		}
		chapterService.saveChapter(chapter);

		model.addAttribute("pid", chapter.getPid());
		model.addAttribute("courseId", chapter.getCourseId());
		model.addAttribute("msg", "新增成功，可继续新增");
		return "chapter-add";
	}

}
